# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
import pymongo

class MongoPipeline(): # Object写不写无所谓
    def __init__(self, mongo_uri, mongo_db):
        self.mongo_uri = mongo_uri
        self.mongo_db = mongo_db

    @classmethod
    def from_crawler(cls, crawler):
        return cls(
            mongo_uri=crawler.settings.get('MONGO_URI'),
            mongo_db=crawler.settings.get('MONGO_DB'),
        )

    def open_spider(self, spider):
        self.client = pymongo.MongoClient(self.mongo_uri)
        self.db = self.client[self.mongo_db]

    def process_item(self, item, spider):
        self.db[item.collection].insert(dict(item))
        return item

    def close_spider(self, spider):
        self.client.close()


'''
cmd命令：
    mysql -u root -p
    输入：123456
    show databases;
    create database images360 default character utf8 collate utf8_general_ci;
    use images360;
    create table images (id varchar(255) primary key, url varchar(255) null, title varchar(255) null, thumb varchar(255) null);
'''

import pymysql

class MysqlPipeline():
    def __init__(self, host, database, user, password, port):
        self.host = host
        self.database = database
        self.user = user
        self.password = password
        self.port = port

    @classmethod
    def from_crawler(cls, crawler):
        return cls(
            host = crawler.settings.get('MYSQL_HOST'),
            database = crawler.settings.get('MYSQL_DATABASE'),
            user = crawler.settings.get('MYSQL_USER'),
            password = crawler.settings.get('MYSQL_PASSWORD'),
            port = crawler.settings.get('MYSQL_PORT'),
        )

    def open_spider(self, spider):
        # 前面的参数可以不指明，但是一旦前面的参数指明，后面的参数必须指明
        self.db = pymysql.connect(host=self.host, user=self.user, password=self.password, database=self.database, port=self.port, charset = 'utf8')
        self.cursor = self.db.cursor()

    def process_item(self, item, spider):
        data = dict(item)
        keys = ', '.join(data.keys())
        values = ', '.join(['%s'] * len(data))
        sql = 'insert into %s (%s) values (%s)' % (item.table, keys, values)
        self.cursor.execute(sql, tuple(data.values()))
        self.db.commit()
        return item

    def close_spider(self, spider):
        self.db.close()


from scrapy import Request
from scrapy.exceptions import DropItem
from scrapy.pipelines.images import ImagesPipeline

class ImagePipeline(ImagesPipeline):
    def file_path(self, request, response=None, info=None):
        '''
        :param request: 当前下载对应的Request对象
        :param response:
        :param info:
        :return: 返回保存的文件名
        '''
        url = request.url
        # 利用split()函数分割链接并提取最后一部分，返回结果
        file_name = url.split('/')[-1]
        return file_name

    def item_completed(self, results, item, info):
        '''
        单个Item完成下载时的处理方法，原因：并不是每张图片都会下载成功，所以我们需要分析下载结果并提出下载失败的图片
        :param results: 该Item对应的下载结果，列表形式，列表每一个元素是一个元组，其中包含了下载或成功的信息
        :param item:
        :param info:
        :return:
        '''
        # 遍历下载结果找出所有成功的下载列表
        image_paths = [x['path'] for ok, x in results if ok]
        # 如果列表为空，那么该Item对应的图片下载失败，随机抛出异常DropItem，该Item忽略。否则返回该Item，说明次Item有效
        if not image_paths:
            raise DropItem('Image Downloaded Failed')
        return item

    def get_media_requests(self, item, info):
        yield Request(item['url'])

'''
官方文档：https://doc.scrapy.org/en/latesst/topics/media-pipeline.html
'''